package com.luoguijia.disk.mybatis.flexigrid;

import com.luoguijia.disk.mybatis.annotation.Columns;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * table 表数据
 * @param <T>
 */
public class TblResponseEntity<T> implements Serializable {

    private Integer total;

    private Integer page;

    private List<TblRowsEntity> rows =
            new ArrayList<TblRowsEntity>();

    private List<Object> columns =
            new ArrayList<>();

    private List<T> rawRecords;

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public List<TblRowsEntity> getRows() {
        return rows;
    }

    public void setRows(List<TblRowsEntity> rows) {
        this.rows = rows;
    }

    public List<Object> getColumns() {
        return columns;
    }

    public void setColumns(List<Object> columns) {
        this.columns = columns;
    }

    public List<T> getRawRecords() {
        return rawRecords;
    }

    public void setRawRecords(List<T> rawRecords) {
        this.rawRecords = rawRecords;
    }

    @Override
    public String toString() {
        return "TblResponseEntity{" +
                "total=" + total +
                ", page=" + page +
                ", rows=" + rows +
                ", columns=" + columns +
                ", rawRecords=" + rawRecords +
                '}';
    }

    public void deal() {
        if(this.rawRecords.size() == 0) {
            return;
        }
        Class<?> classez = this.rawRecords.get(0).getClass();
        Field[] fields = classez.getDeclaredFields();
        for(Field field:fields) {
            if(field.isAnnotationPresent(Columns.class)) {
                columns.add(field.getName());
            }
        }

        TblRowsEntity tblRowsEntity = null;
        T item = null;

        for(int i = 0; i < this.rawRecords.size(); i ++) {
            item = this.rawRecords.get(i);
            tblRowsEntity = new TblRowsEntity(i);
            this.rows.add(tblRowsEntity);
            for(Field field:fields) {
                if(field.isAnnotationPresent(Columns.class)) {
                    field.setAccessible(true);
                    try {
                        tblRowsEntity.addCell(field.get(item));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        tblRowsEntity.addCell(null);
                    }
                }
            }
        }
    }
}
